<?php

namespace app\index\controller;

use think\Db;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use WeChatPay\Formatter;
use WeChatPay\Crypto\AesGcm;
class Index
{

    public function index()
    {
          // 商户号
            // $merchantId = '1677978762';
            $merchantId = '1635074356';

            // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
            $merchantPrivateKeyFilePath = 'file://'.__DIR__.'/pem/apiclient_key.pem';
            $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

            // 「商户API证书」的「证书序列号」
            // $merchantCertificateSerial = '3F7C98F79AD54A79AD8DCFDFAA8CCD88A6F2EE44';
             $merchantCertificateSerial = '7EF3040A2EDD8545D5F07FCE25D62D20F8127E24';

            // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
          
            $platformCertificateFilePath = 'file://'. __DIR__.'/pem/apiclient_cert.pem';
            $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

            // 从「微信支付平台证书」中获取「证书序列号」
            $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
            // dump($platformCertificateSerial );die;
            $platformCertificateSerial ='1F0F0439E1D54499813F6C4BE30AA3F3901535CE';
            // $platformCertificateSerial = '21E4A411BC8CE42285029C3B0F5142ED721246DF';
            // 构造一个 APIv3 客户端实例
            $instance = Builder::factory([
                'mchid'      => $merchantId,
                'serial'     => $merchantCertificateSerial,
                'privateKey' => $merchantPrivateKeyInstance,
                'certs'      => [
                    $platformCertificateSerial => $platformPublicKeyInstance,
                ],
            ]);
try {
    $resp = $instance
    ->chain('v3/pay/transactions/native')
    ->post(['json' => [
        'mchid'        =>  $merchantId,
        'out_trade_no' => 'native12177525012014070332331',
        'appid'        => 'wx416fdb79bc0ad693',
        'description'  => 'Image形象店-深圳腾大-QQ公仔',
        'notify_url'   => 'https://weixin.qq.com/',
        'amount'       => [
            'total'    => 1,
            'currency' => 'CNY'
        ],
    ]]);

    echo $resp->getStatusCode(), PHP_EOL;
    echo $resp->getBody(), PHP_EOL;
} catch (\Exception $e) {
    // 进行错误处理
    echo $e->getMessage(), PHP_EOL;
    if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
        $r = $e->getResponse();
        // echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
        echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
    }
    // echo $e->getTraceAsString(), PHP_EOL;
}
            // 发送请求
         
    }
    public function notify(){
        $data = input($data );
    }

    
}
